package com.socket;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class TcpClient
{
    public static void main(String[] args)
    {
        Socket socket = null;
        OutputStream os = null;
        DataOutputStream dout = null;
        InputStream is = null;
        DataInputStream din = null;
        try
        {
            socket = new Socket("127.0.0.1", 9090);           
            os = socket.getOutputStream();
            dout = new DataOutputStream(os);
            System.out.println("Client : sending data to server");
            dout.writeInt(100);
            dout.writeUTF("This is message from client");
            dout.flush();
            System.out.println("Client : finish sending data to server");
            
            System.out.println("Client : waiting response from server");
            is = socket.getInputStream();
            din = new DataInputStream(is);
            System.out.println("Client : get response from server");
            System.out.println("Server replies : " + din.readUTF());
            
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                dout.close();
                os.close();
                din.close();
                is.close();
                socket.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

}
